package com.ktwlrj.logmanage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktwlrj.logmanage.entity.LogEntity;
import com.ktwlrj.logmanage.mapper.LogMapper;
import com.ktwlrj.logmanage.service.LogService;
import com.ktwlrj.logmanage.util.LogQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志表(Log)业务层实现
 *
 * @author zhouxuanhong
 * @date 2019-04-09 10:25:49
 * @since JDK1.8
 */
@Service
@Slf4j
public class LogServiceImpl extends ServiceImpl<LogMapper, LogEntity> implements LogService {
    private static final double MAX_SIZE = 0.4;
    private static final double MIN_SIZE = 0.01;
    private final LogMapper mapper;

    @Autowired
    public LogServiceImpl(LogMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    @Async
    public void saveLog(LogEntity model) {
        try {
            // 日志加入到阻塞队列
            if (model != null) {
                LogQueue.push(model);
            }
            // 判断队列大小，如果日志数量大于总容量的20%则直接入库,否则交给定时任务入库
            int size = LogQueue.size();
            int totalSize = LogQueue.QUEUE_MAX_SIZE;
            if ((size * 1.0 / totalSize) > (totalSize * MAX_SIZE)) {
                List<LogEntity> list = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    list.add(LogQueue.poll());
                    // 当容量小于总容量的1%时停止入库
                    totalSize = LogQueue.QUEUE_MAX_SIZE;
                    if ((size * 1.0 / totalSize) < (totalSize * MIN_SIZE)) {
                        break;
                    }
                }
                insertLogs(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    @Async
    public void insertLogs(List<LogEntity> logList) {
//        if (!logList.isEmpty()) {
//            mapper.insertList(logList);
//        }
    }
}